//
//  AppDataController.m
//  SnowCovered
//
/*
 
 Copyright (c) 2010, Subodh Shakya, Anand Subba Rao, All Rights Reserved
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */
#import "AppDataController.h"
#import "Product.h"
#import "Category.h"
#import "XMLRPCConnection.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"

@interface AppDataController()
@property (nonatomic, readwrite, retain) NSArray* featuredApps;
@property (nonatomic, readwrite, retain) NSArray* appCategories;
@property (nonatomic, readwrite, retain) NSArray* topApps;
@property (nonatomic, readwrite, retain) NSArray* searchResults;

@property (nonatomic, readwrite, assign) BOOL loadingCategories;

@property (nonatomic, retain) NSOperationQueue* operationQueue;
@property (nonatomic, retain) NSURL* apiURL;

- (NSArray*)parseProducts:(NSArray*)products;
@end

@implementation AppDataController
@synthesize featuredApps;
@synthesize appCategories;
@synthesize topApps;
@synthesize searchResults;
@synthesize operationQueue;
@synthesize apiURL;
@synthesize selectedCategory;


@synthesize loadingCategories;

static AppDataController *_instance = nil;
NSString* LoadingFeaturedApps = @"loadingFeaturedApps";
NSString* FailedLoadingFeaturedApps = @"failedLoadingFeaturedApps";
NSString* FinishedLoadingFeaturedApps = @"finishedLoadingFeaturedApps";
NSString* LoadingTopApps = @"loadingTopApps";
NSString* FailedLoadingTopApps = @"failedLoadingTopApps";
NSString* FinishedLoadingTopApps = @"finishedLoadingTopApps";
NSString* LoadingSpotlightApps = @"loadingSpotlightApps";
NSString* FailedLoadingSpotlightApps = @"failedLoadingSpotlightApps";
NSString* FinishedLoadingSpotlightApps = @"finishedLoadingSpotlightApps";

- (void)getFeaturedApps {
    
    /* make server call */
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                     selector:@selector(operationGetFeaturedApps)
                                                                       object:nil];
    [self.operationQueue addOperation:op];
    [op release];
}

- (void)operationGetFeaturedApps {
    /* make the server call */
    XMLRPCRequest* request = [[XMLRPCRequest alloc] initWithURL:self.apiURL];
    [request setMethod:@"sc.getFeatured" withParameter:self.selectedCategory.categoryID];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LoadingFeaturedApps object:self.selectedCategory];
    
    NSError* error = nil;
    XMLRPCResponse* response = [XMLRPCConnection sendSynchronousXMLRPCRequest:request error:&error]; 

    /* post notification on error */
    if (error || [response isFault]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:FailedLoadingFeaturedApps
                                                            object:self.selectedCategory
                                                          userInfo:[NSDictionary dictionaryWithObject:request forKey:@"request"]];
        return;
    }
    
    /* update featured apps in self.featuredApps */
    NSArray* products = [response object];

    NSArray* fp = [self parseProducts:products];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:FinishedLoadingFeaturedApps
                                                        object:self.selectedCategory
                                                      userInfo:[NSDictionary dictionaryWithObject:fp forKey:@"featuredApps"]];    
}

- (void)getSpotlightApps {
    
    /* make server call */
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                     selector:@selector(operationGetSpotlightApps)
                                                                       object:nil];
    [self.operationQueue addOperation:op];
    [op release];
}

- (void)operationGetSpotlightApps {
    /* make the server call */
    XMLRPCRequest* request = [[XMLRPCRequest alloc] initWithURL:self.apiURL];
    [request setMethod:@"sc.getSpotlight"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LoadingSpotlightApps object:nil];
    
    NSError* error = nil;
    XMLRPCResponse* response = [XMLRPCConnection sendSynchronousXMLRPCRequest:request error:&error]; 
    
    /* post notification on error */
    if (error || [response isFault]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:FailedLoadingSpotlightApps
                                                            object:nil
                                                          userInfo:[NSDictionary dictionaryWithObject:request forKey:@"request"]];
        return;
    }
    
    /* update featured apps in self.featuredApps */
    NSArray* products = [response object];
    
    NSArray* fp = [self parseProducts:products];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:FinishedLoadingSpotlightApps
                                                        object:nil
                                                      userInfo:[NSDictionary dictionaryWithObject:fp forKey:@"spotlightApps"]];    
}

- (void)getCategoriesWithParent:(int)parentCat {
    self.loadingCategories = YES;

    /* make server call */
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                     selector:@selector(operationGetCategoriesWithParent:)
                                                                       object:[NSNumber numberWithInt:parentCat]];
    [self.operationQueue addOperation:op];
    [op release];
}

- (void)operationGetCategoriesWithParent:(NSNumber*)parentCat {
    /* make the server call */
    XMLRPCRequest* request = [[XMLRPCRequest alloc] initWithURL:self.apiURL];
    [request setMethod:@"sc.getCategories" withParameter:parentCat];
    
    NSError* error = nil;
    XMLRPCResponse* response = [XMLRPCConnection sendSynchronousXMLRPCRequest:request error:&error]; 
    
    /* post notification on error */
    if (error || [response isFault]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"XMLRPCError"
                                                            object:error
                                                          userInfo:[NSDictionary dictionaryWithObject:request forKey:@"request"]];
        self.loadingCategories = NO;
        return;
    }
    
    /* update featured apps in self.featuredApps */
    NSArray* categories = [response object];
    
    NSMutableArray* fc = [NSMutableArray array];
    
    if ([categories respondsToSelector:@selector(objectAtIndex:)]) {
        for (NSDictionary* dict in categories) {
            if ([dict respondsToSelector:@selector(valueForKey:)]) {
                Category* newCat = [[Category alloc] init];
                newCat.categoryID = [dict valueForKey:@"cat_id"];
                newCat.categoryName = [dict valueForKey:@"cat_name"];
                [fc addObject:newCat];
            }
        }
    }
    
    self.appCategories = fc;
    self.loadingCategories = NO;
}

- (void)getTopApps {
    /* make server call */
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                     selector:@selector(operationGetTopApps:)
                                                                       object:self.selectedCategory];
    [self.operationQueue addOperation:op];
    [op release];
    
}

- (void)getTopAppsWithCategoryId:(int)catId {
    /* make server call */
    Category* cat = [[Category alloc] init];
    cat.categoryID = [NSNumber numberWithInt:catId];
    
    NSInvocationOperation* op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                     selector:@selector(operationGetTopApps:)
                                                                       object:cat];
    [cat release];
    
    [self.operationQueue addOperation:op];
    [op release];    
}

- (void)operationGetTopApps:(Category*)category {
    /* make the server call */
    XMLRPCRequest* request = [[XMLRPCRequest alloc] initWithURL:self.apiURL];
    [request setMethod:@"sc.getPopular" withParameter:category.categoryID];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LoadingTopApps object:category];
    
    NSError* error = nil;
    XMLRPCResponse* response = [XMLRPCConnection sendSynchronousXMLRPCRequest:request error:&error]; 
    
    /* post notification on error */
    if (error || [response isFault]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:FailedLoadingTopApps
                                                            object:category
                                                          userInfo:[NSDictionary dictionaryWithObject:request forKey:@"request"]];
        return;
    }
    
    /* update featured apps in self.featuredApps */
    NSArray* products = [response object];
    
    NSArray* tp = [self parseProducts:products];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:FinishedLoadingTopApps
                                                        object:category
                                                      userInfo:[NSDictionary dictionaryWithObject:tp forKey:@"topApps"]];    
}

- (void)searchAppsWithString:(NSString*)theString {
}


- (NSOperationQueue*)operationQueue {
    if (!operationQueue) {
        operationQueue = [[NSOperationQueue alloc] init];
        [operationQueue setMaxConcurrentOperationCount:5];
    }
    
    return operationQueue;
}

/* clear objects that can be created later */
+ (void)dispose {
    _instance.operationQueue = nil;
    _instance.apiURL = nil;
}

- (NSURL*)apiURL {
    if (!apiURL) {
        apiURL = [NSURL URLWithString:@"http://isnowcovered.com/SCRPC.ashx"];
    }
    
    return apiURL;
}

- (NSArray*)parseProducts:(NSArray*)products {
    NSMutableArray* fp = [NSMutableArray array];
    
    if ([products respondsToSelector:@selector(objectAtIndex:)]) {
        for (NSDictionary* dict in products) {
            if ([dict respondsToSelector:@selector(valueForKey:)]) {
                Product* newProduct = [[Product alloc] init];
                newProduct.productName = [dict valueForKey:@"product_name"];
                newProduct.productID = [[dict valueForKey:@"product_id"] stringValue];
                newProduct.publisherName = [dict valueForKeyPath:@"publisher.pub_name"];
                newProduct.summary = [dict valueForKey:@"summary"];
                newProduct.price = [dict valueForKey:@"price"];
                newProduct.imageURL = [dict valueForKey:@"product_imageurl"];
                newProduct.publishedDate = [dict valueForKey:@"publish_date"];
                [fp addObject:newProduct];
                [newProduct release];
            }
        }
    }
    
    return fp;
}

#pragma mark -
#pragma mark singleton

                
+ (AppDataController*)sharedController
{
    if (_instance == nil) {
        _instance = [[super allocWithZone:NULL] init];
    }
    return _instance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedController] retain];
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}
@end
